<?php namespace App\Repositories\Eloquent\User;

use App\Models\UserToken;
use App\Repositories\User\UserTokenRepositoryInterface;
use Carbon\Carbon;

class UserTokenRepository implements UserTokenRepositoryInterface
{
    /**
     * 存储用户token
     *
     * @param $user_id
     * @param $token
     * @param $expired_at
     * @param $ip
     *
     * @return bool
     */
    public function store($user_id, $token, $expired_at, $ip)
    {
        $model = new UserToken();
        $model->user_id = $user_id;
        $model->token = $token;
        $model->expired_at = $expired_at;
        $model->ip = (string)$ip;

        return $model->save();
    }

    /**
     * 获取token用户id
     *
     * @param $token
     *
     * @return int|null
     */
    public function getUserIdByToken($token)
    {
        $user_token = UserToken::query()
            ->where('token', $token)
            ->where('expired_at', '>=', Carbon::now()->toDateTimeString())
            ->first();

        if ($user_token) {
            return $user_token->user_id;
        }
    }
}
